package com.fjrz.bbxwj.main.host.side

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ConvertUtils
import com.module.lemlin.view.LoadingDialog
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.app.RZApplication
import com.fjrz.bbxwj.entity.UserMe
import com.fjrz.bbxwj.entity.VideoDraft
import com.fjrz.bbxwj.main.host.adpter.VideoDraftAdapter
import com.fjrz.bbxwj.main.video.VideoEditingActivity
import com.fjrz.bbxwj.mode.vm.UserViewModel
import com.module.lemlin.view.DialogHintPopup
import com.fjrz.bbxwj.popup.PasswordSettingPopup
import com.fjrz.bbxwj.popup.PasswordVerifyPopup
import com.module.lemlin.rxhttp.code
import com.module.lemlin.view.LoginAuthPopup
import kotlinx.android.synthetic.main.activity_sketch_box.*
import kotlinx.android.synthetic.main.activity_sketch_box.mSmartRefreshLayout
import java.lang.StringBuilder

class MainSketchBoxActivity : ViewModeActivity<UserViewModel>() {

    companion object {
        private const val EXTRA_KEY_TITLE = "EXTRA_KEY_TITLE"
        private const val EXTRA_KEY_TYPE = "EXTRA_KEY_TYPE"
        fun open(activity: Activity, title: String, type: Int) {
            val intent = Intent(activity, MainSketchBoxActivity::class.java)
            intent.putExtra(EXTRA_KEY_TITLE, title)
            intent.putExtra(EXTRA_KEY_TYPE, type)
            activity.startActivity(intent)
        }
    }


    private val sketchAdapter: VideoDraftAdapter = VideoDraftAdapter()

    private val pwdSetHintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = this,
            onConfirm = {
                pwdSettingPopup.setPhone(RZApplication.userInfoMe()?.mobile)
                    .setTitle("访问密码设置")
                    .showPopupWindow()
            },
            onCancel = {
                finish()
            })
    }

    private val deleteHintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = this,
            onConfirm = {
                var videoIds = StringBuilder()
                sketchAdapter.videoSelectList().forEach {
                    videoIds.append(it.id).append(",")
                }
                videoIds = videoIds.deleteCharAt(videoIds.lastIndexOf(","))
                viewModel.videoDelete(videoIds = videoIds.toString())
                deleteHintPopup.dismiss()
            },
            onCancel = {
                deleteHintPopup.dismiss()
            })
    }

    private val pwdVerifyPopup: PasswordVerifyPopup by lazy {
        PasswordVerifyPopup(context = this, onForget = {
            pwdSettingPopup.setPhone(RZApplication.userInfoMe()?.mobile)
                .setTitle("忘记密码？")
                .showPopupWindow()
        }, onConfirm = {
            viewModel.setPasswordSaveInterim(it)
        }, onFinish = {
            finish()
        })
    }

    private val pwdSettingPopup: PasswordSettingPopup by lazy {
        PasswordSettingPopup(context = this, onGetCode = { phone ->
            //获取验证码
            viewModel.userSmsSend(phone, event = "set_pwd")
        }, onConfirm = { smsCode, password, confirmPassword ->
            viewModel.userSetPwd(smsCode, password, confirmPassword)
        })
    }

    override val layoutResId: Int
        get() = R.layout.activity_sketch_box

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override fun stateBar(): StatusBar {
        return StatusBar(color = R.color.colorWhite, view = frameSketchBoxBar)
    }

    override fun initView() {
        ivSketchBoxBack.setOnClickListener { this.finish() }

        intent?.getStringExtra(EXTRA_KEY_TITLE)?.let {
            tvSketchBoxTitle.text = it
        }

        rvSketchBoxBody.apply {
            val decoration = SpacingItemDecoration(
                vGap = ConvertUtils.dp2px((15f)), hGap = ConvertUtils.dp2px((15f))
            )
            addItemDecoration(decoration)
        }.adapter = sketchAdapter

        //列表item点击监听
        sketchAdapter.setOnItemClickListener { _, _, position ->
            val itemData: VideoDraft = sketchAdapter.getItem(position)
            VideoEditingActivity.openModify(activity = this, videoDraft = itemData)
        }

        //取消选择监听
        cbSketchBoxAction.setOnCheckedChangeListener { buttonView, isChecked ->
            buttonView.text = if (isChecked) "取消" else "选择"
            sketchAdapter.isAction = isChecked
            frameSketchBottom.visibility = if (isChecked) View.VISIBLE else View.GONE
        }

        //删除点击监听
        tvSketchBoxDelete.setOnClickListener {
            deleteHintPopup.setTextTitle("提示")
                .setTextMessage("确定删除视频内容，不可修复")
                .setTextCancel("取消")
                .setTextConfirm("删除")
                .showPopupWindow()
        }

        //下拉刷新监听
        mSmartRefreshLayout.setOnRefreshListener {
            initDataRefresh()
        }
        //加载更多刷新监听
        mSmartRefreshLayout.setOnLoadMoreListener {
            initDataLoadMore()
        }
    }

    override fun initData() {
        initDataRefresh()
    }

    override fun onRestart() {
        super.onRestart()
        initDataRefresh()
    }

    private fun initDataRefresh() {
        val type: Int = intent?.getIntExtra(EXTRA_KEY_TYPE, (0))
            ?: return
        if (type == 1) {
            viewModel.userMyVideos(status = 0)
        } else if (type == 2) {
            viewModel.setPasswordSaveInterim(viewModel.passwordLiveData.value)
        }
    }

    private fun initDataLoadMore() {
        val type: Int = intent?.getIntExtra(EXTRA_KEY_TYPE, (0))
            ?: return
        if (type == 1) {
            viewModel.userMyVideos(status = 0, isLoadMore = true)
        } else if (type == 2) {
            viewModel.passwordLiveData.value?.let {
                viewModel.userPrivateDraftVideos(password = it, isLoadMore = true)
            }
        }
    }

    override fun initViewMode() {

        viewModel.passwordLiveData.observe(this as LifecycleOwner, Observer { pwd ->
            if (pwd.isNullOrEmpty()) {
                viewModel.userMe()
            } else {
                viewModel.userPrivateDraftVideos(pwd)
            }
        })

        viewModel.videoDraftLiveData.observe(this as LifecycleOwner, Observer { response ->
            val status: Status = responseStatus1LiveData(response.status, response.throwable)
            if (status == Status.FAILURE && intent?.getIntExtra(EXTRA_KEY_TYPE, (0)) == 2) {
                toast(response.throwable?.code,response.throwable?.msg)
            }
            if (status != Status.SUCCESS)
                return@Observer
            val isLoadMore: Boolean = response.httpData?.loadMore ?: false
            val videoDrafts: MutableList<VideoDraft> =
                response.httpData?.data?.data ?: mutableListOf()
            if (videoDrafts.isNullOrEmpty()) {
                sketchAdapter.setEmptyView(createViewEmptyNull(hint = "暂无数据"))
            }
            if (isLoadMore) {
                sketchAdapter.addData(videoDrafts)
            } else {
                sketchAdapter.setNewInstance(videoDrafts)
            }
            if (videoDrafts.size < viewModel.limit) {
                sketchAdapter.setFooterView(createViewFooter())
                mSmartRefreshLayout.setEnableLoadMore(false)
            } else {
                sketchAdapter.removeAllFooterView()
                mSmartRefreshLayout.setEnableLoadMore(true)
            }
            if (pwdVerifyPopup.isShowing)
                pwdVerifyPopup.dismiss()
            cbSketchBoxAction.visibility =
                if (sketchAdapter.data.size == 0) View.GONE else View.VISIBLE
        })

        viewModel.userMeLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (responseStatus1LiveData(response.status, response.throwable) != Status.SUCCESS)
                return@Observer
            val userMe: UserMe = response.httpData?.data
                ?: return@Observer
            if (userMe.password_set != 1) {
                pwdSetHintPopup.setTextTitle("提示")
                    .setTextMessage("您暂时尚未设置访问密码")
                    .setTextCancel("暂不设置")
                    .setTextConfirm("去设置")
                    .showPopupWindow()
            } else {
                if (!pwdVerifyPopup.isShowing)
                    pwdVerifyPopup.showPopupWindow()
            }
        })

        viewModel.userSmsLiveData.observe(this as LifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> if (pwdSettingPopup.isShowing)
                    pwdSettingPopup.startCodeDownTime()
                Status.FAILURE -> {
                    toast(response.throwable?.code,response.throwable?.msg)
                }
                Status.SUCCESS -> response.httpData?.let {
                    toast(message = it.msg ?: "发送成功")
                }
            }
        })

        viewModel.userSetPwdLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (responseStatus2LiveData(response.status, response.throwable) != Status.SUCCESS)
                return@Observer
            if (pwdSetHintPopup.isShowing)
                pwdSetHintPopup.dismiss()
            if (pwdSettingPopup.isShowing)
                pwdSettingPopup.dismiss()
            viewModel.userMe()
        })

        viewModel.videoDeleteLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (responseStatus2LiveData(response.status, response.throwable) != Status.SUCCESS)
                return@Observer
            initDataRefresh()
        })

        sketchAdapter.selectCountLiveData.observe(this as LifecycleOwner, Observer { count ->
            tvSketchBoxDelete.isEnabled = count != 0
            tvSketchBoxDelete.text =
                if (count == 0) "删除" else "删除(${count})"
        })
    }


    override fun onEventMainThread(any: Any) {
        if (any !is LoginAuthPopup.Action)
            return
        if (any == LoginAuthPopup.Action.ACTION_LOGIN_SUCCESS) {
            initDataRefresh()
        }
    }

    private fun responseStatus1LiveData(status: Status, throwable: Throwable?): Status {
//        mSmartRefreshLayout.setEnableRefresh(status != Status.START)
        if (status == Status.START) {
            sketchAdapter.setEmptyView(createViewEmptyLoad())
        } else if (status == Status.FAILURE) {
            mSmartRefreshLayout.finishLoadMore((false))
            mSmartRefreshLayout.finishRefresh((false))
            sketchAdapter.setEmptyView(createViewEmptyNull(hint = throwable?.msg ?: "未知错误"))
        } else {
            mSmartRefreshLayout.finishLoadMore((true))
            mSmartRefreshLayout.finishRefresh((true))
        }
        return status
    }

    private fun responseStatus2LiveData(status: Status, throwable: Throwable?): Status {
        if (status == Status.START) LoadingDialog.show(
            context = this, resId = R.layout.dialog_load_style_1
        ) else if (status == Status.FAILURE) {
            LoadingDialog.dismiss()
            toast(throwable?.code,throwable?.msg)
        } else {
            LoadingDialog.dismiss()
        }
        return status
    }

    override fun onDestroy() {
        super.onDestroy()
        if (pwdVerifyPopup.isShowing)
            pwdVerifyPopup.dismiss()
        if (pwdSetHintPopup.isShowing)
            pwdSetHintPopup.dismiss()
    }

    override fun onBackPressed() {
        if (sketchAdapter.isAction) {
            cbSketchBoxAction.isChecked = false
        } else {
            super.onBackPressed()
        }
    }

}